package platform

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"fmt"
)

// 微小用户信息
type UserInfo struct {
	NickName  string `json:"nickName"`
	AvatarUrl string `json:"avatarUrl"`
	Gender    int    `json:"gender"`
	City      string `json:"city"`
	Province  string `json:"province"`
	Country   string `json:"country"`
	Watermark struct {
		AppID     string `json:"appid"`
		Timestamp int64  `json:"timestamp"`
	} `json:"watermark"`
}

// 解密微小或抖小用户信息
func DecryptUserInfo(encryptedData, sessionKey, iv string) (*UserInfo, error) {
	aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
	if err != nil {
		return nil, fmt.Errorf("base64 decode sessionKey failed: %v", err)
	}

	cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return nil, fmt.Errorf("base64 decode encryptedData failed: %v", err)
	}

	ivBytes, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return nil, fmt.Errorf("base64 decode iv failed: %v", err)
	}

	block, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, fmt.Errorf("aes new cipher failed: %v", err)
	}

	mode := cipher.NewCBCDecrypter(block, ivBytes)
	mode.CryptBlocks(cipherText, cipherText)

	// PKCS#7 Unpadding
	length := len(cipherText)
	unpadding := int(cipherText[length-1])
	cipherText = cipherText[:(length - unpadding)]

	var userInfo UserInfo
	if err := json.Unmarshal(cipherText, &userInfo); err != nil {
		return nil, fmt.Errorf("json unmarshal failed: %v", err)
	}

	return &userInfo, nil
}
